import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pipedream_lighting/src/bluetooth/send_data.dart';
import 'package:pipedream_lighting/src/home/blue_data_model.dart';

import '../search/search_view.dart';
import '../tool/assets.dart';
import 'pick_image.dart';
import 'rotation_btn.dart';
import 'view_model.dart';

class Myhome extends StatefulWidget {
  const Myhome({super.key});

  @override
  State<Myhome> createState() => _MyHomeWidgetState();
}

class _MyHomeWidgetState extends State<Myhome> {
  late final CircularColorPicker _coloCircular;
  late kTooltip _tooltip;
  final ImagePicker _picker = ImagePicker();
  late final _colorList;
  XFile? _pickedImage;
  bool rgb_select = false;
  List<String> btn_on_icons = [assets.mic_on, assets.turn_on, assets.setup_on];
  List<String> btn_off_icons = [assets.mic_off, assets.turn_off, assets.setup_off];
  List<bool> btn_status = [false, false, false];
  List<String> btn_tips = ['mic', 'on/off', 'setup'];
  List<DataModel> device_data_list = [];
  List<int> color_select_list = [];
  String? _bright;
  bool _isSending = false;
  void initState() {
    super.initState();
    getBright();
    listenBluetooth(context);

    ///色盘
    _coloCircular = CircularColorPicker(
        cirulaImage: assets.color,
        pointImage: assets.color_point,
        padding: const EdgeInsets.only(left: 0, right: 0),
        onChange: (p0) {
          if (color_select_list.isNotEmpty && p0[0] != 0 && p0[1] != 0 && p0[2] != 0) {
            color_select_list = p0;
            _colorList.color = p0.decimal;
            _setSignColor();
          }
        });

    ///色列表
    _colorList = ColorListView(onChange: (p0, p1) {
      var value = p0;
      value = (0xFF << 24) | (value & 0x00FFFFFF);
      _coloCircular.kstate.setInitialColor(Color(value));
      color_select_list = p0.bytes;
      _setSignColor();
    });
    _colorList.leftIcon = assets.add;
    _colorList.rightIcon = assets.sum;
  }

  // @override
  // void dispose() {
  //   // 恢复默认的系统 UI 模式
  //   SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  //   super.dispose();
  // }

  void updataDeviceData(DataModel model) {
    setState(() => device_data_list.add(model));
  }

  ///弹出下拉框
  void popTooltipView(BuildContext context) {
    _tooltip = kTooltip(
        context: context,
        autoHidden: false,
        child: PickImage(onClick: () {
          setState(() => rgb_select = false);
          _tooltip.hide();
          _pickImage();
        }));
    _tooltip.show(completion: () => setState(() => rgb_select = false));
  }

  ///底部三个按钮事件
  void tapAction(BuildContext context, int index) {
    switch (index) {
      case 0:
        if (btn_status[1] == false) {
          return;
        }
        btn_status[index] = !btn_status[index];
        SendData.send('麦克风', btn_status[index]);
      case 1:
        btn_status[index] = !btn_status[index];
        btn_status[0] = btn_status[index] ? btn_status[0] : false;
        for (var model in device_data_list) {
          model.isOn = btn_status[index];
          SendData.send('开关', btn_status[index]);
        }
      case 2:
        btn_status[index] = true;
        SearchView search = SearchView();
        search.show(context, completion: () {
          setState(() => btn_status[2] = false);
        });
      default:
    }
  }

  ///旋转按钮的事件
  void rotationMethod(int index, double angle, int grees, dynamic changeValue) {
    print('=================>   changevalue =${changeValue}');
    switch (index) {
      case 0:
        for (var model in device_data_list) {
          dynamic speed = 32 - changeValue.round();
          model.speed = speed;
          SendData.send('指定颜色模式', model);
        }
      case 1:
        var rotate = rotateModel_list[index];
        dynamic value = icon_list.length - 1 - changeValue.round();
        for (var model in device_data_list) {
          model.mode = icon_list[value].values.first;
          SendData.send('指定颜色模式', model);
        }
        setState(() {
          rotate.backImg = icon_list[value].keys.first;
        });
      case 2:
        dynamic bright = changeValue;
        _bright = bright.toString();
        saveBright(_bright ?? '1');
        _setSignColor();
      default:
    }
  }

  ///设置单色颜色
  void _setSignColor() {
    if (color_select_list.length >= 3) {
      String bright = _bright ?? '1';
      for (var model in device_data_list) {
        int red = (color_select_list[0] * bright.float / 10.0).round();
        int green = (color_select_list[1] * bright.float / 10.0).round();
        int blue = (color_select_list[2] * bright.float / 10.0).round();
        SendData.send('单色模式', [red, green, blue]);
      }
    }
  }

  ///选择图片
  Future<void> _pickImage() async {
    _pickedImage = await _picker.pickImage(source: ImageSource.gallery);
    if (_pickedImage != null) {
      ByteData byteData = await _convertToByteData(_pickedImage!);
      _coloCircular.kstate.updateImage(byteData);
    }
    setState(() {});
  }

  Future<ByteData> _convertToByteData(XFile file) async {
    // 读取文件内容
    final bytes = await File(file.path).readAsBytes();
    // 将字节数组转换为 ByteData
    return ByteData.sublistView(Uint8List.fromList(bytes));
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕的宽度
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;
    GlobalConfig.scaleH = screenHeight / 667.0;

    // 设置状态栏背景颜色和图标颜色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏背景色
      statusBarIconBrightness: Brightness.light, // 状态栏图标颜色 (白色图标)
    ));
    return Scaffold(
      appBar: null,
      body: Stack(
        children: [
          ///背景
          Positioned(
            child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(image: AssetImage(assets.bg), fit: BoxFit.fitHeight),
              ),
            ),
          ),

          ///内容
          Positioned(
            top: 40,
            left: 0,
            right: 0,
            bottom: 20,
            child: Column(
              children: [
                ///LOGO2
                SizedBox(height: 50, child: Image.asset(assets.LOGO2)),

                ///取色器，选取本地照片
                /* Positioned(
              top: 110,
              right: 20,
              child: Builder(builder: (context) {
                return IconButton(
                  tooltip: '取色器',
                  enableFeedback: true,
                  icon: Image.asset(rgb_select ? assets.RGB_select : assets.RGB,
                      fit: BoxFit.fitHeight, width: 40),
                  onPressed: () {
                    popTooltipView(context);
                    setState(() => rgb_select = !rgb_select);
                  },
                );
              })),*/
                ///间隔
                const SizedBox(height: 20),

                ///删除选取本地的照片
                SizedBox(
                  child: _pickedImage == null
                      ? Container(
                          height: 0,
                          color: Colors.orange,
                        )
                      : IconButton(
                          padding: const EdgeInsets.all(0),
                          iconSize: 48,
                          enableFeedback: true,
                          icon: const Icon(
                            Icons.cancel,
                            color: Color_bg_view,
                          ),
                          onPressed: () {
                            setState(() {
                              _pickedImage = null;
                              _coloCircular.kstate.updateImage(null);
                            });
                          },
                        ),
                ),

                ///原色色盘
                Flexible(flex: 14, child: _coloCircular),

                ///间隔
                Flexible(flex: 2, child: Container()),

                ///彩色列表
                Flexible(flex: 3, child: _colorList),

                ///间隔
                const SizedBox(height: 20),

                ///三个旋钮
                Flexible(
                    flex: 5,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: List.generate(3, (index) {
                        return kRotationBtn(
                          data: rotateModel_list[index],
                          onChange: (angle, degrees, value) {
                            ///截断一下快读发送数据
                            if (_isSending == false) {
                              _isSending = true;
                              rotationMethod(index, angle, degrees, value);
                              Future.delayed(const Duration(milliseconds: 50), () {
                                _isSending = false;
                              });
                            }
                          },
                          onChangeEnd: (angle, degrees, value) {},
                        );
                      }),
                    )),

                ///间隔
                const SizedBox(height: 20),

                ///底部三个按钮
                Flexible(
                  flex: 3,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: List.generate(3, (index) {
                      return IconButton(
                        tooltip: btn_tips[index],
                        enableFeedback: true,
                        padding: EdgeInsets.zero, // 去掉默认的 padding
                        icon: Image.asset(
                          btn_status[index] ? btn_on_icons[index] : btn_off_icons[index],
                          fit: BoxFit.fitHeight,
                          // width: 60,
                          // height: 60,
                        ),
                        onPressed: () {
                          setState(() => tapAction(context, index));
                        },
                      );
                    }),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

///蓝牙的一些监听
extension _MyHomeStateExtesion on _MyHomeWidgetState {
  void listenBluetooth(BuildContext context) {
    ///监听蓝牙外设连接状态
    BluetoothManager.instance.connectionStateStream.listen((value) {
      var state = value.values.first;
      switch (state) {
        case BluetoothConnectionState.connected:
          EasyLoading.showSuccess('Connect successfully');
          listen();
          SendData.send('查询数据', '');
        case BluetoothConnectionState.disconnected:
          EasyLoading.showSuccess('disConnected!', duration: const Duration(milliseconds: 1500));
        case BluetoothConnectionState.connecting:
          break;
        case BluetoothConnectionState.disconnecting:
          print('设备断开连接中');
          break;
      }
    });

    ///监听蓝牙广播状态
    BluetoothManager.instance.bluetoothStateStream.listen((state) {
      switch (state) {
        case BluetoothAdapterState.on:
          break;
        case BluetoothAdapterState.off:
          EasyLoading.showInfo('Bluetooth turned off');
        default:
      }
    }, onError: (error) {
      EasyLoading.showInfo('${error.message}');
    });
  }

  void listen() {
    ///监听数据回调
    BluetoothManager.instance.read(
        service_uuid: read_service,
        characteristics_uuid: read_uuid,
        onResponse: (data) {
          print('收到蓝牙上传的数据是 == ${data.toHexstr(' |')}');
          if (data.length >= 12 && data[0] == 0x66) {
            btn_status[1] = data[2] == 0x23;
            DataModel model = DataModel(
                name: data[1].bytes.toHexstr(),
                isOn: data[2] == 0x23,
                mode: data[3],
                isPlay: data[4] == 0x20,
                speed: data[5],
                red: data[6],
                green: data[7],
                blue: data[8],
                warmWhite: data[9],
                version: data[10]);
            if (device_data_list.any(($0) => $0.name == model.name) == false) {
              updataDeviceData(model);
            }
          }
        });
  }
}

///保存数据
extension _MyHomeStateExtesion2 on _MyHomeWidgetState {
  Future<void> saveBright(String groupName) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('bright', groupName);
  }

  Future<void> getBright() async {
    final prefs = await SharedPreferences.getInstance();
    _bright = prefs.getString('bright');
  }
}
